<template>
  <div>
    <div style="margin-bottom: 5px">
      <el-input v-model="name"  placeholder="请输入名字" suffix-icon="el-icon-search" style="width: 300px"
              @keyup.enter.native="loadPost"></el-input>
      <el-select v-model="roleId" filterable placeholder="请选择角色" style="margin-left: 5px;width: 300px" @change="loadPost">
        <el-option
            v-for="item in roleIds"
            :key="item.value"
            :label="item.label"
            :value="item.value">
        </el-option>
      </el-select>
      <el-button style="margin-left: 5px" type="primary" icon="el-icon-search" @click="loadPost">查询</el-button>
      <el-button style="margin-left: 5px" type="success" icon='el-icon-refresh-left' @click="reset">重置</el-button>
      <el-button style="margin-left: 5px" type="warning" icon='el-icon-circle-plus-outline' @click="add">新增</el-button>
    </div>
  <el-table :data="tableData" style="width: 100%"
    :header-cell-style="{background: '#f3f6fd', color: '#211e1e'}"

  >
    <el-table-column prop="id" label="ID" min-width="40%" align="center">
    </el-table-column>
    <el-table-column prop="no" label="账号" min-width="100%" align="center">
    </el-table-column>
    <el-table-column prop="name" label="姓名" min-width="100%" align="center">
    </el-table-column>
    <el-table-column prop="age" label="年龄" min-width="40%" align="center">
    </el-table-column>
    <el-table-column prop="sex" label="性别" min-width="60%" align="center">
      <template v-slot="scope">
        <el-tag
            :type="scope.row.sex === 0 ? 'primary' : 'success'"
            disable-transitions>{{scope.row.sex === 0 ? '男' : '女'}}</el-tag>
      </template>
    </el-table-column>
    <el-table-column prop="roleId" label="角色" min-width="100%" align="center">
      <template v-slot="scope">
        <el-tag
            :type="scope.row.roleId === 0 ?'danger' :(scope.row.roleId === 1 ?'warning' : 'info')"
            disable-transitions>{{scope.row.roleId === 0 ? '超级管理员' : (scope.row.roleId === 1 ? '普通用户' : '游客')}}</el-tag>
      </template>
    </el-table-column>
    <el-table-column prop="phone" label="电话" min-width="100%" align="center">
    </el-table-column>
    <el-table-column prop="operate" label="操作" min-width="80%" align="center">
      <template v-slot="scope">
        <el-button type="text" icon="el-icon-edit" size="medium" @click="mod(scope.row)">编辑</el-button>
        <el-popconfirm
            title="确定删除吗？"
            @confirm="del(scope.row.id)"
            style="margin-left: 5px"
        >
          <el-button slot="reference" type="text" icon="el-icon-delete" size="medium" >删除</el-button>
        </el-popconfirm>
      </template>
    </el-table-column>
  </el-table>
    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageNum"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
    </el-pagination>

    <el-dialog
        title="提示"
        :visible.sync="centerDialogVisible"
        width="30%"
        center>
      <el-form ref="form" :rules="rules" :model="form" label-width="80px">
        <el-form-item label="账号" prop="no">
          <el-col :span="20">
            <el-input v-model="form.no" :disabled="disabled_index"></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="名字" prop="name">
          <el-col :span="20">
            <el-input v-model="form.name" ></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="密码" prop="password" >
          <el-col :span="20">
            <el-input v-model="form.password" type="password"></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-col :span="20">
            <el-input v-model="form.age" ></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="form.sex">
            <el-radio label="0">男</el-radio>
            <el-radio label="1">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-col :span="20">
            <el-input v-model="form.phone" ></el-input>
          </el-col>
        </el-form-item>
      </el-form>
        <span slot="footer" class="dialog-footer" >
    <el-button @click="centerDialogVisible=false">取 消</el-button>
    <el-button type="primary" @click="save">确 定</el-button>
        </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  name: "Main",
  components: {
  },

  data(){
    let checkAge = (rule, value, callback) => {
      if(value>150){
        callback(new Error('年龄输入过大'));
      }else{
        callback();
      }
    };
    let checkDuplicate =(rule,value,callback)=>{
      if(this.form.id){
        return callback();
      }
      this.$axios.get(this.$httpUrl+"/user/findByNo?no="+this.form.no).then(res=>res.data).then(res=>{
        if(res.code!=200){
          callback()
        }else{
          callback(new Error('账号已经存在'));
        }
      })
    };
    return {
      disabled_index:false,
      tableData: [],
      pageSize:10,
      pageNum:1,
      total:0,
      name:'',
      roleId:'',
      roleIds:[
        {
          value: '0',
          label: '超级管理员'
        }, {
          value: '1',
          label: '普通用户'
        },{
          value: '2',
          label: '游客'
        },
      ],
      centerDialogVisible:false,
      form:{
        id:'-1',
        name:'',
        no:'',
        password:'',
        age:'',
        phone:'',
        sex:'0',
        roleId:'1'
      },
      rules:{
        no: [
          { required: true, message: '请输入账号', trigger: 'blur' },
          { min: 6, max: 18, message: '长度在 6 到 18 个字符', trigger: 'blur' },
          {validator:checkDuplicate,trigger: 'blur'}
        ],
        name: [
          { required: true, message: '请输入名字', trigger: 'blur' },
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 18, message: '长度在 6 到 18 个字符', trigger: 'blur' }
        ],
        age: [
          {required: true, message: '请输入年龄', trigger: 'blur'},
          {min: 1, max: 3, message: '⻓度在 1 到 3 个位', trigger: 'blur'},
          {pattern: /^([1-9][0-9]*){1,3}$/,message: '年龄必须为正整数字',trigger: "blur"},
          {validator:checkAge,trigger: 'blur'}
        ],
        phone: [
          {required: true,message: "手机号不能为空",trigger: "blur"},
          {pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: "请输入正确的手机号码", trigger: "blur"}
        ]
      }
    }
  },
  created() {
    // this.loadGet();
    this.loadPost();
  },
  methods:{
    resetForm(){
      this.$refs.form.resetFields();
    },
    mod(row){
      console.log(row)
      this.centerDialogVisible=true
      this.$nextTick(()=>{
        this.form.id = row.id
        this.form.no = row.no
        this.form.name = row.name
        this.form.password = row.password
        this.form.age = row.age+''
        this.form.sex = row.sex+''
        this.form.phone = row.phone
        this.form.roleId = row.roleId
        this.disabled_index = true
      })

    },
    del(id){
      console.log(id)
      this.$axios.get(this.$httpUrl+'/user/delete?id='+id).then(res=>res.data).then(res=>{
        console.log(res)
        if (res.code==200){
          this.$message({
            showClose: true,
            message: '操作成功',
            type: 'success'
          });
          this.centerDialogVisible=false
          this.loadPost()
        }else{
          this.$message({
            showClose: true,
            message: '操作失败',
            type: 'error'
          });
        }
      })
    },
    loadGet(){
      this.$axios.get(this.$httpUrl+'/user/list').then(res=>res.data).then(res=>{
        console.log(res)
      })
    },
    loadPost(){
      this.$axios.post(this.$httpUrl+'/user/listPage1',{
        pageSize:this.pageSize,
        pageNum:this.pageNum,
        params:{
          name:this.name,
          roleId:this.roleId
        }
      }).then(res=>res.data).then(res=>{
        console.log(res)
        if (res.code==200){
          this.tableData=res.data
          this.total=res.total
        }else{
          alert("获取数据失败")
        }
      })
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pageNum=1
      this.pageSize=val
      this.loadPost()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.pageNum=val
      this.loadPost()
    },
    reset(){
      this.name=''
      this.roleId=''
      this.loadPost()
    },
    doMod(){
      this.$axios.post(this.$httpUrl+'/user/update',this.form).then(res=>res.data).then(res=>{
        console.log(res)
        if (res.code==200){
          this.$message({
            showClose: true,
            message: '操作成功',
            type: 'success'
          });
          this.centerDialogVisible=false
          this.loadPost()
        }else{
          this.$message({
            showClose: true,
            message: '操作失败',
            type: 'error'
          });
        }
      })
    },
    dosave(){
      this.$axios.post(this.$httpUrl+'/user/add',this.form).then(res=>res.data).then(res=>{
        console.log(res)
        if (res.code==200){
          this.$message({
            showClose: true,
            message: '操作成功',
            type: 'success'
          });
          this.centerDialogVisible=false
          this.loadPost()
        }else{
          this.$message({
            showClose: true,
            message: '操作失败',
            type: 'error'
          });
        }
      })
    },
    save(){
        this.$refs.form.validate((valid) => {
          if (valid) {
            if (this.form.id=='-1'){
              console.log("新增")
              this.dosave();
              this.form.id='-1'
            }else{
              console.log("修改")
              this.doMod();
              this.form.id='-1'
            }
          } else {
            console.log('error submit!!');
            return false;
          }
        });
    },
    add(){

      this.centerDialogVisible=true
      this.disabled_index = false
      this.$nextTick(()=>{
        this.resetForm()
      })
    }
  }
}
</script>

<style scoped>

</style>